package com.tool4j.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tool4j.common.RoleEnum;
import com.tool4j.common.UserStatusEnum;
import com.tool4j.entity.User;
import com.tool4j.entity.params.LoginParams;
import com.tool4j.mapper.UserMapper;
import com.tool4j.service.UserService;
import com.tool4j.util.IdGenerator;
import com.tool4j.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Deng.Weiping
 * @since 2023-10-28 11:27:36
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findList(User params) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class);
        return userMapper.selectList(query);
    }

    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean insert(User user) {
        return save(user);
    }

    @Override
    public boolean update(User user) {
        return updateById(user);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public User exists(LoginParams params) {
        LambdaQueryWrapper<User> historyQuery = Wrappers.lambdaQuery(User.class)
                .eq(User::getPhoneNum, params.getAccount())
                .or()
                .eq(User::getEmail, params.getAccount());
        User history = userMapper.selectOne(historyQuery);
        //处理历史账号
        if (history != null && StrUtil.isBlank(history.getAccount())) {
            history.setAccount(params.getAccount());
            history.setPassword(Md5Util.getMD5(params.getAccount()));
            userMapper.updateById(history);
            return history;
        }

        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getAccount, params.getAccount())
                .eq(User::getPassword, Md5Util.getMD5(params.getPassword()));
        return userMapper.selectOne(query);
    }

    @Override
    public Boolean delAccount(Long userId) {
        User user = findByUserId(userId);
        user.setStatus(UserStatusEnum.DEL.getValue());
        userMapper.updateById(user);
        return true;
    }

    @Override
    public User findByUserId(Long userId) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getUserId, userId);
        return userMapper.selectOne(query);
    }

    @Override
    public User findByPhoneNum(String phoneNum) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getPhoneNum, phoneNum);
        return userMapper.selectOne(query);
    }

    @Override
    public User findByEmail(String email) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getEmail, email);
        return userMapper.selectOne(query);
    }

    @Override
    public void updateRole(Long userId, String vipType) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getUserId, userId);
        User user = userMapper.selectOne(query);
        user.setRole(vipType);
        userMapper.updateById(user);
    }

    @Override
    public void modifyPwd(LoginParams params) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getAccount, params.getAccount());
        User user = userMapper.selectOne(query);
        Assert.notNull(user, "账号不存在");
        user.setPassword(Md5Util.getMD5(params.getPassword()));
        userMapper.updateById(user);
    }

    @Override
    public User init(LoginParams params) {
        log.info("初始化用户：{}", params);
        //用户不存在，创建用户
        User user = new User();
        user.setAccount(params.getAccount());
        user.setPassword(Md5Util.getMD5(params.getPassword()));
        user.setRegion(params.getRegion());
        user.setSourceIp(params.getIp());
        Long userId = IdGenerator.generateId();
        user.setUserId(userId);
        user.setRole(RoleEnum.USER.getValue());

        if (StrUtil.isNotBlank(params.getPhoneNum())) {
            user.setPhoneNum(params.getPhoneNum());
        } else if (StrUtil.isNotBlank(params.getEmail())) {
            user.setEmail(params.getEmail());
        } else {
            user.setName("新用户");
        }
        userMapper.insert(user);
        return user;
    }

    /**
     * 将手机号的中间4位替换为*号
     *
     * @param phoneNumber 原始手机号
     * @return 替换后的手机号
     */
    private String maskPhoneNumber(String phoneNumber) {
        // 截取前3位和后4位，中间4位替换为*
        return phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
    }

}